<template>
  <div>
    <!--    面包屑导航区域-->
    <el-breadcrumb :separator-icon="ArrowRight">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!--    卡片视图区域-->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input
              placeholder="请输入内容"
              v-model="querInfo.query"
              clearable
              @clear="getUserList()"
          >
            <template #append>
              <el-button @click="getUserList">
                <el-icon>
                  <Search/>
                </el-icon>
              </el-button>
            </template>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加</el-button>
        </el-col>
      </el-row>

      <!--      用户列表区域-->
      <el-table :data="userList" border stripe style="width: 100%">
        <el-table-column type="index" label="#" width="50"/>
        <el-table-column prop="username" label="姓名" width="180"/>
        <el-table-column prop="email" label="邮箱" width="180"/>
        <el-table-column prop="mobile" label="电话" width="180"/>
        <el-table-column prop="role_name" label="角色" width="180"/>
        <el-table-column prop="mg_state" label="状态" width="180">
          <template #="scope">
            <el-switch
                v-model="scope.row.mg_state"
                @change="userStateChanged(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="mg_state" label="操作">
          <template #="scope">
            <el-button type="primary" @click="showEditDialog(scope.row.id)">
              <el-icon>
                <Edit/>
              </el-icon>
            </el-button>
            <el-tooltip effect="dark" content="分配角色" placement="top">
              <el-button type="primary">
                <el-icon>
                  <Share/>
                </el-icon>
              </el-button>
            </el-tooltip>

            <el-button type="primary" @click="removeUserByID(scope.row.id)">
              <el-icon>
                <Delete/>
              </el-icon>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          v-model:current-page="querInfo.pagenum"
          v-model:page-size="querInfo.pagesize"
          :page-sizes="[1, 2, 5, 10]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </el-card>
    <!--    添加用户的对话框-->
    <el-dialog
        v-model="addDialogVisible"
        title="添加用户"
        width="50%"
        @close="addDialogClosed"
    >
      <span>
      <el-form
          ref="addFormRef"
          :model="addForm"
          :rules="addFormRefs"
          label-width="70px"
      >
    <el-form-item label="用户名" prop="username">
      <el-input v-model="addForm.username"/>
    </el-form-item>
        <el-form-item label="密码" prop="password">
      <el-input v-model="addForm.password"/>
          </el-form-item>
        <el-form-item label="邮箱" prop="email">
      <el-input v-model="addForm.email"/>
          </el-form-item>
        <el-form-item label="手机号" prop="mobile">
      <el-input v-model="addForm.mobile"/>
    </el-form-item>
      </el-form>
        </span>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addUser">
          确认
        </el-button>
      </span>
      </template>
    </el-dialog>
    <!--    修改用户的对话框-->
    <el-dialog
        v-model="editDialogVisible"
        title="修改用户"
        width="50%"
    >
      <el-form
          ref="editFormRef"
          :model="editForm"
          :rules="editFormRules"
          label-width="70px"
          status-icon
          @close="editDialogClosed"
      >
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled/>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="editForm.email"/>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="editForm.mobile"/>
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="editUserInfo">
          确定
        </el-button>
      </span>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import { ElMessageBox } from 'element-plus'

export default {
  data() {
    // 验证邮箱的规则
    var checkEmail = (rule, value, cb) => {
      //   验证邮箱的正则表达式
      const regEamil = /^([a-zA-Z0-9])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])/
      if (regEamil.test(value)) {
        //   合法邮箱
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    }
    // 验证手机号的规则
    var checkmobile = (rule, value, cb) => {
      //   验证手机号的正则表达式
      const regmobile = /^[1][3,4,5,7,8][0-9]{9}$/

      if (regmobile.test(value)) {
        //   合法邮箱
        return cb()
      }
      cb(new Error('请输入合法的手机号'))
    }
    return {
      querInfo: {
        query: '',
        // 当前页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 2
      },
      userList: [],
      total: 10,
      // 隐藏对话框
      addDialogVisible: false,
      //   添加用户的表单数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 添加用户表单的验证规则对象
      addFormRefs: {
        username: [
          {
            required: true, message: '请入用户名',
            trigger: 'blur'
          }, {
            min: 3,
            max: 10,
            message: '用户名在3~10个字之间'
          }
        ],
        password: [
          {
            required: true, message: '请入密码',
            trigger: 'blur'
          }, {
            min: 3,
            max: 10,
            message: '密码在3~10个字之间'
          }
        ],
        email: [
          {
            required: true, message: '请入邮箱',
            trigger: 'blur'
          },
          {
            validator: checkEmail, trigger: 'blur'
          }
        ],
        mobile: [
          {
            required: true, message: '请入手机号',
            trigger: 'blur'
          },
          {
            validator: checkmobile, trigger: 'blur'
          }
        ]
      },
      // 控制修改用户对话框的显示与隐藏
      editDialogVisible: false,
      // 查询用户信息对象
      editForm: {},
      //   用户修改的验证规则
      editFormRules: {
        email: [
          {
            required: true, message: '请入邮箱',
            trigger: 'blur'
          },
          {
            validator: checkEmail, trigger: 'blur'
          }
        ],
        mobile: [
          {
            required: true, message: '请入手机号',
            trigger: 'blur'
          },
          {
            validator: checkmobile, trigger: 'blur'
          }
        ]

      }
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const {data: res} = await this.$http.get('users', {params: this.querInfo})
      if (res.meta.status !== 200) return this.$message.error(res.msg)
      // console.log(res)
      this.userList = res.data.users
      // console.log(this.userList)

    },
    handleSizeChange(newSize) {
      this.querInfo.pagesize = newSize
      this.getUserList()
    },
    handleCurrentChange(newPage) {
      this.querInfo.pagenum = newPage
      this.getUserList()
    },
    async userStateChanged(userinfo) {
      const {data: res} = await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state
        return this.$message.error('更新用户状元失败')
      }
      this.$message.success('用户更新成功')
    },
    // 监听添加用户对话框的关闭事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    //   点击按钮,添加新用户
    addUser() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        //   可以发起添加用户的请求
        const {data: res} = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) {
          this.$message.error('添加失败')
        }
        this.$message.success('添加用户成功')
        //   隐藏添加用户的对话框
        this.addDialogVisible = false
        this.getUserList()
      })
    },
    // 展示用户编辑的对话框
    async showEditDialog(id) {
      const {data: res} = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('查询用户信息失败')
      }
      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 监听修改用户对话框的关闭事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 修改用户信息并提交
    editUserInfo() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        //   发起修改用户数据信息的请求
        const {data: res} = await this.$http.put('users/' + this.editForm.id, {
          email: this.editForm.email,
          mobile: this.editForm.mobile
        })
        if (res.meta.status !== 200) {
          return this.$message.error('更新用户失败')
        }
        //   关闭对话框
        this.editDialogVisible = false
        //   刷新数据
        this.getUserList()
        //   提示修改成功
        this.$message.success('更新用户成功')

      })
    }
    ,
    //   删除用户信息
    async removeUserByID(id) {
      const configs = await
          ElMessageBox.confirm(
              '此操作将永久删除用户. 是否继续?',
              '提示',
              {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
              }
          ).catch(err => err)
      if (configs !== 'confirm') {
        return this.$message.info('已取消删除')
      }

      const {data: res} = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除用户失败')
      }
      this.$message.success('删除用户失败')
      this.getUserList()
    }
  }


}
</script>
<style lang="scss" scoped>
.el-card {
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.15);
}

.el-table {
  margin-top: 15px;
  font-size: 12px;
}
</style>